package com.jack.hhitseat.task;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jack.hhitseat.bean.AppBean;
import com.jack.hhitseat.bean.User;
import com.jack.hhitseat.service.HttpClient;
import com.jack.hhitseat.service.impl.LogServiceImpl;
import com.jack.hhitseat.utils.MyUtils;

public class DirectRequest extends Thread {
	private final Logger logger = LoggerFactory.getLogger(MyRunnable.class);
	private static HttpClient httpClient = new HttpClient();
	private static LogServiceImpl logServiceImpl = (LogServiceImpl) AppBean.getBean("logServiceImpl");
	private User u;
	private Map<String, String> sessionMap = new HashMap<>();
	private final static String KEY = "16";
	
	private final static  String BOOK_URL = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/reserve.aspx?" +
			"&dev_id={dev_id}" + "&type={type}" + "&start={start}" + "&end={end}" +
			"&start_time={start_time}" + "&end_time={end_time}"+"&number={number}" + "&act={act}" +
			"&_={_}"; 
	
	public DirectRequest() {
	}
	
	public DirectRequest(User u
			, Map<String, String> sessionMap) {
		this.u = u;
		this.sessionMap = sessionMap;
	}
	
	@Override
	public void run() {
		String stuNum = u.getStuNum();
		String[] seats = u.getSeat().split(",");
		String session = sessionMap.get(stuNum);
		Map<String, Object> qzParparamMap = new HashMap<String, Object>();

    	String yyrq = MyUtils.getNextDate(); 
		qzParparamMap.put("type","dev");
		qzParparamMap.put("start",yyrq+"+08:00");
		//qzParparamMap.put("end",yyrq+"+22:00");
		qzParparamMap.put("end",yyrq+"+21:00");		//暑假时间
		qzParparamMap.put("start_time","800"); 
		//qzParparamMap.put("end_time","2200");
		qzParparamMap.put("end_time","2100");		//暑假时间
		qzParparamMap.put("number", KEY);			//万能钥匙Key
		qzParparamMap.put("act","set_resv");
		
		for (String str : seats) {
			String seatNumb = str.split("=")[0];
			String result = "";
			qzParparamMap.put("dev_id", seatNumb); 
			String sjc = System.currentTimeMillis()+"";
			qzParparamMap.put("_",sjc);
			
			result = httpClient.qz2(BOOK_URL, session, qzParparamMap);
			if(result.contains("成功")) {
				logServiceImpl.addLog(stuNum, seatNumb);
				break;
			}else if(result.contains("已有预约")) {
				break;
			}
			logger.warn("{}==={}==={}", u.getUserName() ,
					result.split("\"msg\":\"")[1].split("\",\"data\":")[0] , str.split("=")[1]);
		}
	}
}
